package com.ynny.chapter07_3.service;

import com.ynny.chapter07_3.dao.UserDao;
import com.ynny.chapter07_3.entity.User;
import com.ynny.chapter07_3.entity.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserDao userDao;


    @Override
    public int register(UserDTO dto) {

        //1.检查用户名是否存在
        User repeatUser = userDao.selectUserByUserName(dto.getUsername());
        if (repeatUser != null){

            return 205;
        }
        //2.注册

        //将hobby集合 转成字符串

        List<Integer> hobby = dto.getHobby();

        //根据 ，拼接字符串
        StringBuilder sb = new StringBuilder();
        for (Integer hobbyId : hobby) {
            sb.append(hobbyId).append(",");
        }
        String hobbys = sb.toString().substring(0, sb.length() - 1);

        User registerUser = new User();
        registerUser.setUsername("[新用户]" + dto.getUsername());
        registerUser.setPassword(dto.getPassword());
        registerUser.setSex(dto.getSex());
        registerUser.setIdentity(dto.getIdentity());
        registerUser.setHobby(hobbys);
        registerUser.setImageUrl(dto.getImageUrl());


        int i = userDao.insertUser(registerUser);

        if (i != 1){
            return 502;
        }

        //3.注册成功 送积分

        return 200;
    }
}
